package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Slf4j
//@CrossOrigin  //解决跨域请求问题 但是比较繁琐 在每个controller中都得加
public class UserController {

    @DubboReference
    private UserService userService;
    /**
     * 用户登录接口
     * @param loginParam
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginParam loginParam, HttpSession session){
        log.info("用户登录接口"+loginParam);
        User user = userService.findByUserName(loginParam.getUsername());
        log.info("查询结果为"+user);
        if(null==user){
            return new Result(false, MessageConst.LOGIN_FAIL);
        }
//        if(!user.getPassword().equals(loginParam.getPassword())){
//            return new Result(false, MessageConst.LOGIN_FAIL);
//        }
        session.setAttribute("user", user);
        return new Result(true,MessageConst.LOGIN_SUCCESS);
    }

    @GetMapping("/getUsername")
    public Result getUsername() {
        //
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (null != principal && principal instanceof org.springframework.security.core.userdetails.User) {
            org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) principal;
            return new Result(true, MessageConst.GET_USERNAME_SUCCESS, user.getUsername());
        }
        return new Result(false, MessageConst.GET_USERNAME_FAIL);
    }


    @RequestMapping("/loginSuccess")
    public Result loginSuccess(){
        return new Result(true,MessageConst.LOGIN_SUCCESS);
    }
    @RequestMapping("/loginFail")
    public Result loginFail(){
        return new Result(false,MessageConst.LOGIN_FAIL);
    }

}
